package antidestiny.utilib.ui.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.os.Build;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.Button;

import antidestiny.utilib.Aide;
import antidestiny.utilib.R;

/**
 * Created by Hero on 2017/1/1.
 */

public class TTFButton extends Button {
    public TTFButton(Context context, AttributeSet attrs) {
        super(context,attrs);
        loadFont(context,attrs);
    }
    public TTFButton(Context context,AttributeSet attrs,int defStyleAttr){
        super(context,attrs,defStyleAttr);
        loadFont(context,attrs);
    }
    @android.support.annotation.RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public TTFButton(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        loadFont(context, attrs);
    }

    /**
     * 加载ttf字体
     *
     * @param context 环境
     * @param attrs   从这里获取信息
     */
    private void loadFont(Context context, @Nullable AttributeSet attrs) {
        if (isInEditMode())return;
        if (attrs == null) return;
        TypedArray array=context.obtainStyledAttributes(attrs, R.styleable.icon_font);
        String fontAssetPath = array.getString(R.styleable.icon_font_ttf);
        array.recycle();

        if (fontAssetPath != null) {
            Typeface iconfont = Typeface.createFromAsset(context.getAssets(), fontAssetPath);
            if (iconfont == null) throw new RuntimeException("加载字体失败了。");
            setTypeface(iconfont);
            Aide.t(this+"加载字体成功:"+fontAssetPath);
        }else{
            Aide.t("未找到信息。");
        }
    }
}
